#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <string.h>
#include <arpa/inet.h>
#include <ctype.h>
#include <signal.h>
#include <sys/wait.h>
#include <errno.h>
#include <pthread.h>

typedef struct sockinfo
{
  int fd;
  struct sockaddr_in addr;
  pthread_t id;
  // SockInfo* next; // 尝试用链表来实现不知道可不可以
} SockInfo;
// 进程回收的回调函数
void* worker(void* arg)
{
  SockInfo* info = (SockInfo*)arg;
  char ip[64];
  while (1)
  {
    printf("client IP: %s, port: %d\n", inet_ntop(AF_INET, &info->addr.sin_addr.s_addr, ip, sizeof(ip)), ntohs(info->addr.sin_port));
    char buf[1024] = {0};
    int len = read(info->fd, buf, sizeof(buf));
    if (len == -1)
    {
      perror("read error");
      // exit(1);
      pthread_exit(NULL);
    }
    else if (len == 0)
    {
      printf("客户端断开了链接\n");
      close(info->fd);
      break;
    }
    else
    {
      printf("recv buf: %s\n", buf);
      write(info->fd, buf, len);
    }
  }
  return NULL;
}

int main(int argc, const char *argv[])
{
  if (argc < 2)
  {
    printf("./a.out port");
    exit(1);
  }
  int port = atoi(argv[1]);
  // 创建套接字
  int lfd = socket(AF_INET, SOCK_STREAM, 0);
  // 绑定本地IP和端口
  struct sockaddr_in serv;
  memset(&serv, 0, sizeof(serv));
  serv.sin_port = htons(port);
  serv.sin_addr.s_addr = INADDR_ANY;
  serv.sin_family = AF_INET;
  int flag = 1;
  setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag));
  bind(lfd, (const struct sockaddr *)&serv, sizeof(serv));

  // 监听
  listen(lfd, 128);
  printf("start accept.......\n");

  // 等待接收连接请求
  int i = 0;
  SockInfo info[256];
  for(i=0; i<sizeof(info)/sizeof(info[0]); ++i)
  {
    info[i].fd = -1;
  }
  socklen_t len = sizeof(struct sockaddr_in);
  // cfd 通信套接字

  while (1)
  {
    // 选一个没有被占用的最小的数组的元素
    for(i=0; i<256; ++i)
    {
      if(info[i].fd == -1)
        break;
    }
    if(i == 256)
      break;
    // 父进程接受连接请求
    info[i].fd = accept(lfd, (struct sockaddr *)&info[i].addr, &len);
    printf("connect sucessful\n");
    // 线程分离
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
    pthread_create(&info[i].id, &attr, worker, &info[i]);
    pthread_attr_destroy(&attr);
    // pthread_detach(info[i].id);
    // i++;
  }

  pthread_exit(NULL);
  return 0;
}
